<?php
class CabinBooking extends DataObject {
	static $db = array(
		"NumberOfPersons" => "Int",
		"Name" => "Varchar(255)",
		"FirstName" => "Varchar(255)",
		"Street" => "Varchar(255)",
		"Zip" => "Varchar(10)",
		"City" => "Varchar(255)",
		"Country" => "Varchar(255)",
		"TelNumber" => "Varchar(255)",
		"Email" => "Varchar(255)",
		'DateFrom' => 'Date',
		'DateTo' => 'Date',
	);
	
	static $has_one = array(
		'Cabin' => 'Cabin',
	);	
	
	public function getCMSFields_forPopup() {
		$fields = self::getFormFields();
		
		return $fields;
	}
	
	static public function getFormFields() {
		$dateFrom = new CalendarPickerField('DateFrom','von *');
		$dateFrom->setMinimumDate(date('Y-m-d'));
		
		$dateTo = new CalendarPickerField('DateTo','bis *');
		$dateTo->setMinimumDate(date('Y-m-d'));
		

		
		
		$fieldset = new FieldSet(
			new NumericField('NumberOfPersons','Anzahl Personen *','',3),
			$dateFrom,
			$dateTo,
			new TextField('Name','Nachname *'),
			new TextField('FirstName','Vorname *'),
			new TextField('Street','Strasse / Nr *'),
			new TextField('Zip','PLZ *'),
			new TextField('City','Ort *'),
			new TextField('Country','Land *'),
			new TextField('TelNumber','Telefonnummer *'),
			new TextField('Email','Email *')
		);
		return $fieldset;
	}
}

class CabinBookingFields extends RequiredFields {


   
	function php($data) {
		$valid = parent::php($data);

   		$cabin = DataObject::get_one('Cabin','`Cabin`.ID = ' . $data['CabinID']);
		
		if ($valid && (strtotime($data['DateFrom']) == null)) {
        	$this->validationError("DateFrom", 'Bitte geben Sie ein Datum an',"message required");
            $valid = false;
		} 
		if (strtotime($data['DateTo']) == null) {
        	$this->validationError("DateTo", 'Bitte geben Sie ein Datum an',"message required");
            $valid = false;
		} 
   		
		if ($valid && strtotime($data['DateFrom']) >= strtotime($data['DateTo'])) {
        	$this->validationError("DateFrom", 'Datum "von" darf nicht jünger oder gleich sein als "bis"',"message required");
            $valid = false;
		}  	
		if ($valid && (strtotime($data['DateFrom']) < strtotime(date('Y-m-d')) || strtotime($data['DateTo']) < strtotime(date('Y-m-d')) )) {
        	$this->validationError("DateFrom", 'Datum liegt bereits in der Vergangenheit',"message required");
            $valid = false;
		} 	
		if ($valid && !$cabin->checkIfAvailable($data['DateFrom'],$data['DateTo'])) {
        	$this->validationError("DateFrom", "Die Hütte ist in diesem Zeitraum nicht Verfügbar!","message required");
            $valid = false;
		}
      	return $valid;
	}
}

class CabineBookingObjectManager_Popup extends DataObjectManager_Popup {
   function __construct($controller, $name, $fields, $validator, $readonly, $dataObject) {
      parent::__construct($controller, $name, $fields, $validator, $readonly, $dataObject);
      $oVal = new CabinBookingFields(array('NumberOfPersons'));
      $oVal->setForm($this);
      $this->validator = $oVal;
   }
}
 

?>